package com.algrithom.math;

import java.util.PriorityQueue;

public class Solution15 {
    
    public int minOperations(int[][] grid,int x){
        PriorityQueue<Integer> pqMax = new PriorityQueue<>((a,b) -> b - a);
        PriorityQueue<Integer> pqMin = new PriorityQueue<>();
        int left = grid[0][0] % x;
        for (int[] arr : grid) {
            for (int num : arr) {
                if (num % x != left) {
                    return -1;
                }
                if (pqMax.isEmpty() || num <= pqMax.peek()) {
                    pqMax.offer(num);
                    if (pqMax.size() > pqMin.size() + 1) {
                        pqMin.offer(pqMax.poll());
                    }
                } else {
                    pqMin.offer(num);
                    if (pqMin.size() > pqMax.size()) {
                        pqMax.offer(pqMin.poll());
                    }
                }
            }
        }
        int argv = pqMax.peek();
        int ans = 0;
        for (int[] arr : grid) {
            for (int num : arr) {
                ans += Math.abs((argv - num) / x);
            }
        }
        return ans;
    }
}